<template>
  <div style="margin-bottom: 30px; ">
    <div style="float:left;">
      <el-text class="mx-1"> 用户名：</el-text>
      <el-input v-model="search" clearable style="width: 200px" placeholder="输入书名" />
    </div>
    <div class="block" style="float:left;">
      <el-text class="mx-1">借书日期</el-text>
      <el-date-picker v-model="value1" type="date" placeholder="Pick a date" :default-value="new Date(2010, 9, 1)" />
    </div>
    <div class="block" style="float:left;">
      <el-text class="mx-1">还书日期</el-text>
      <el-date-picker v-model="value1" type="date" placeholder="Pick a date" :default-value="new Date(2010, 9, 1)" />
    </div>
    <el-button type="primary" icon="Search" style="margin-left: 30px;">搜索</el-button>
  </div>
  <!-- <el-button type="primary" :disabled="login.data.right == 'common'" icon="Edit" circle color:red></el-button> -->
  <el-table :data="borrowInfoList" :cell-style="cellStyle" :span-method="spanMethod" border style="width: 100%">

    <el-table-column label="借书人" prop="username" align="center" />
    <el-table-column label="ID" prop="borrowId" align="center" />
    <el-table-column label="书名" prop="bookName" align="center" />
    <el-table-column label="借书日期" prop="date1" align="center" :formatter="dateFormat" />

    <el-table-column label="还书日期" prop="date2" align="center" :formatter="dateFormat" />
    <el-table-column label="操作" align="center">
      <!-- 使用template中的作用域插槽，
      它的作用是在外部获取组件内的数据 ,
      这里是为了获取这一行的数据，
      我们让slot-scope值为scope，那么由scope.row就可以得到数据了 -->
      <template #default="scope">
        <el-button type="primary" v-if="login.data.aid ==1 && scope.row.date2 == null"
          @click="notify(scope.row)">催还</el-button>

      </template>
    </el-table-column>
  </el-table>
  <div>
    <mypage :total="total" ref="page"></mypage>
  </div>
</template>

<script lang="ts" setup>
import mypage from '../components/page.vue'
import axios from "axios";
import { ElMessage, TableColumnCtx } from 'element-plus';
import { Delete, Edit, Search, Share, Upload } from '@element-plus/icons-vue'

import { ref, reactive, computed, onMounted, onBeforeMount, toRefs } from 'vue'
//导入时间库 npm install moment --save
import moment from "moment";
//按需导入
const search = ref();//定义简单数据类型
const borrowInfoList = ref([]);//定义复杂数据类型
const total = ref(0);
const login = reactive({})

/*日期处理*/
const dateFormat = (row, column) => {
  var date = row[column.property];
  if (date === undefined || date == null) {
    return ''
  }
  return moment(date).format("YYYY-MM-DD")
};

const compareDates = ((targetDate) => {
  targetDate = new Date(targetDate)
  var currentDate = new Date(); // 获取当前日期
  console.log(currentDate > targetDate)
  if (currentDate > targetDate && Math.abs((currentDate - targetDate)) / (1000 * 60 * 60 * 24 * 30) >= 3) {
    return true; // 若目标日期早于当前日期相差超过三个月，则返回true
  } else {
    return false; // 否则返回false
  }
})

const cellStyle = (({ row, column, rowIndex, columnIndex }) => {
  var date = row.date1;
  if (compareDates(date) && row.date2 == null && column.property == "date1") {
    return {

      "color": "red",
      "font-size": "20px",
      "font-family": "微软雅黑",
      "font-weight": 'italic'

    }
  }
})




// 获取当前时间
var currentDate = new Date();

// 将当前时间加上3个月



const handleEdit = (id) => {
  console.log(id);
};//自定义方法

const handleDelete = (id) => {
  console.log(id);
}
onBeforeMount(() => {
  login.data = JSON.parse(sessionStorage.getItem("user"));
  console.log("onBeforeMount")
  console.log(login.data)
})
onMounted(() => {
  getBorrowInfoList()

})//生命周期函数的变化加了on 去掉了created

const getBorrowInfoList = () => {
  let url = "";

  if (login.data.aid == 1)
    url = "/book/getBorrowBookInfoByID/0";
  else
    url = "/book/getBorrowBookInfoByID/" + login.data.uid;
  axios.get(url).then(res => {
    if (res.data.code == 200) {
      borrowInfoList.value = res.data.result
    }

    // total.value = res.data.total
  })
}

let cellList: any[] = [] // 单元格数组
let count: number = 0 // 计数

const computeCell = (borrowInfoList: any[]) => {
  cellList = []
  count = 0
  for (let i = 0; i < borrowInfoList.length; i++) {
    if (i === 0) {
      // 先设置第一项
      cellList.push(1); // 初为1，若下一项和此项相同，就往cellList数组中追加0
      count = 0; // 初始计数为0
    } else {
      if (borrowInfoList[i].username == borrowInfoList[i - 1].username) {
        cellList[count] += 1; // 增加计数
        cellList.push(0); // 相等就往cellList数组中追加0
      } else {
        cellList.push(1); // 不等就往cellList数组中追加1
        count = i; // 将索引赋值为计数
      }
    }
  }
}



interface SpanMethodProps {
  row: StoragePoolItem
  column: TableColumnCtx<StoragePoolItem>
  rowIndex: number
  columnIndex: number
}

const sortArray = (x: any, y: any) => {
  if (x.username < y.username) { return -1 }
  else if (x.username > y.username) { return 1 }
  else { return 0 }
}

const spanMethod = ({
  rowIndex,
  columnIndex,
}: SpanMethodProps) => {
  computeCell(borrowInfoList.value.sort(sortArray))
  if (columnIndex === 0) {
    const fRow = cellList[rowIndex]
    const fCol = fRow > 0 ? 1 : 0
    return {
      rowspan: fRow, // 合并的行数
      colspan: fCol // 合并的列数，为0表示不显示
    }
  }
}

const notify = ((row) => {
  const data = {
    uid: row.uid,
    msg: "你于" + moment(row.data1).format("YYYY-MM-DD") + "借的" + row.bookName + "已经到期请按时还书"

  }
  axios.post('/message/insertMessage', data).then(res => {
    if (res.data.code == 200) {
      ElMessage({
        type: "success",
        message: res.data.msg,
      });
    } else {
      ElMessage({
        type: "error",
        message: res.data.msg,
      });
    }
  })

})

</script>
<style scoped>
.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}

.demo-date-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
  display: inline-block;
}

.demo-date-picker .block:last-child {
  border-right: none;
}

.demo-date-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
</style>